package com.example.nacos.controller;


import java.sql.*;
import java.util.Date;


public class ClickhouseBatchDemo {

    private static String username = "cebrisk";
    private static String password = "cebrisk";
    private static String address = "jdbc:clickhouse://192.168.88.47:9000/chdb";
//private static String address = "jdbc:clickhouse://192.168.88.47:8123/chdb";

    public static void main(String[] args) throws Exception {

        batchInsertDemo();
    }


    /**
     * 批量插入数据  clickhouse 是分析型数据库无需考虑传统意义上的事务
     * @throws Exception
     */
    public static void batchInsertDemo() throws Exception {
        Connection connection = null;

        try {
            connection = getConnection();
            System.out.println("clickhouse批量插入开始"+new Date());
            PreparedStatement pstmt = connection
                    .prepareStatement("INSERT INTO etl_test  ( id, name )  VALUES (  ?, ?  )");
            // clickhouse 最多批量插入数据 447条记录
            for (int i = 0; i < 447; i++) {
                String id = "10" + i;
                String sku = "sku20231108" + i;
                pstmt.setString(1, id);
                pstmt.setString(2, sku);

                pstmt.addBatch();
            }
            pstmt.executeBatch();
            System.out.println("clickhouse批量插入成功"+new Date());
        } finally {
            close(connection);
        }
    }

    public static Connection getConnection() {
        try {
            Class.forName("com.github.housepower.jdbc.ClickHouseDriver");
//            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
            Connection conn = DriverManager.getConnection(address, username, password);
            System.out.println("Connected to ClickHouse database!");
            // 在这里执行其他操作，比如插入数据
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public static void close(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
